//
//  AutomationViewController.m
//  OST
//
//  Created by mac on 13-7-6.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "AutomationViewController.h"
#import "Common.h"
#import "SetData.h"
#import "StatusData.h"
#import "PersistableInfo.h"
#import "CameraData.h"
#import "ChangeInfoDialog.h"
#import "WISInterfaces.h"
#import "wis.h"
#import "Utitlity.h"
#import "MMProgressHUD.h"
#import "SWTableViewCell.h"
#import "JSONKit.h"
#import "TimingSettingViewController.h"

@interface AutomationViewController ()

@property (strong, nonatomic) NSMutableString *strMutableModeReqResponse;

@end

@implementation AutomationViewController
@synthesize ids;
@synthesize cameras;



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    resultItem = [[NSMutableArray alloc] init];
    tcpResultItem = [[NSMutableArray alloc] init];

    closeNextPage = YES;
    threadLoadData = NO;
    
    BottomView *bottomView = [self addBottomView];
    bottomView.btn_camera.hidden = NO;
    [bottomView.btn_camera addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];

    bottomView.btn_all_power.hidden = NO;
    [bottomView.btn_all_power addTarget:self action:@selector(openAll:) forControlEvents:UIControlEventTouchUpInside];

    dataTableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - bottomView.frame.size.height);
    
    [self refreshData];
    
    resultItem = [[NSMutableArray alloc] init];
    timer=[NSTimer scheduledTimerWithTimeInterval:3
                                          target:self
                                        selector:@selector(updateDevStatusChangeWithHttp)
                                        userInfo:nil
                                         repeats:YES];
    
    count = 0;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (isLoaded == NO )
        {
            isLoaded = YES;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"获取列表失败" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
            [alert show];
        }
    });

    [self requestGetRoomList];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [timer invalidate];
    timer = nil;
    isLoaded = YES;
}

- (void)backToDecice
{
//    [self.navigationController popViewControllerAnimated:YES];
}

-(void)openAll:(UIButton *)sender
{
    UIActionSheet *menu = [[UIActionSheet alloc]
                           initWithTitle: nil
                           delegate:self
                           cancelButtonTitle:@"取消"
                           destructiveButtonTitle:nil
                           otherButtonTitles:@"添加设备",@"删除设备",@"全部打开",@"全部关闭",nil];//@"全部打开",@"全部关闭"
    menu.tag = 200;
    [menu showInView:self.view];
   
}

-(void)openCamera
{
    [activity startAnimating];
    
    ipUrl = [Utitlity judgeipUrl];
    
    if (ipUrl)
    {
        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=3",ipUrl];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            self.cameras = responseObject;
            
            if (!responseObject) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] )
            {
                
                NSArray *devList = [retJsonData objectForKey:@"data"];
                self.cameras = devList;
                
                UIActionSheet *menu = [[UIActionSheet alloc]
                                       initWithTitle: @"请选择"
                                       delegate:self
                                       cancelButtonTitle:nil
                                       destructiveButtonTitle:nil
                                       otherButtonTitles:nil];
                menu.tag = 100;
                
                
                
                for (NSDictionary *dict in self.cameras)
                {
                    [menu addButtonWithTitle:[dict objectForKey:@"Alias"]];
                }
                [menu addButtonWithTitle:@"取消"];
                menu.cancelButtonIndex = menu.numberOfButtons-1;
                NSLog(@"111111");
                [menu showInView:self.view];
            }
            else
            {
                [self openCamera];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }else
    {
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_CMD_CAM_LIST_GET cmdLength:32 withData:(void *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String] callRecivedBlock:^(id data) {
            
            [activity stopAnimating];
            self.cameras = data;
            
            if (!data) return;
            NSDictionary *retJsonData = data;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                NSArray *devList = [retJsonData objectForKey:@"data"];
                self.cameras = devList;
                
                UIActionSheet *menu = [[UIActionSheet alloc]
                                        initWithTitle: @"请选择"
                                        delegate:self
                                        cancelButtonTitle:nil
                                        destructiveButtonTitle:nil
                                        otherButtonTitles:nil];
                menu.tag = 100;
                NSMutableArray *btnArr = [[NSMutableArray alloc] init];
                for (NSDictionary *dict in self.cameras)
                {
                    [btnArr addObject:[dict objectForKey:@"Alias"]];
                }
                for (NSString *str in btnArr) {
                    [menu addButtonWithTitle:str];
                }
                [menu addButtonWithTitle:@"取消"];
                menu.cancelButtonIndex = menu.numberOfButtons-1;
                [menu showInView:self.view];
            }
        }];
    }
}

#pragma mark -添加Add a device
//___________________________________________________

//- (void)deleteOneDeviceIn
//{
//    
//    
//    ipUrl = [Utitlity judgeipUrl];
//    
//    
//    if (ipUrl)
//    {
//        NSString *deleStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=2",ipUrl];
//        
//        [Utitlity commonHTTPMethod:deleStr responseType:stringType success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            if (!responseObject || ![responseObject isKindOfClass:[NSData class]]) return;
//            
//            NSLog(@"add-添加设备1阶段:%@",responseObject);
//            
//            NSString * responseStr = [[NSString alloc] initWithBytes:[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding];
//            NSDictionary *item = [responseStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
//            NSArray *tempArr = [item objectForKey:@"data"];
//            NSDictionary *dic = [tempArr firstObject];
//            NSString *zid = dic[@"ZID"];
//            
//            PersistableInfo *info = (PersistableInfo *)[PersistableInfo findFirstByCriteria:@"where zid='%@'",zid];
//            if(info)
//            {
//                [info delete:zid];
//            }
//            
//            NSString *status = item[@"state"];
//            if ([status isEqualToString:@"Success"])
//            {
//                NSLog(@"添加设备1阶段，删除设备成功");
//                [self addOneDevice];
//            }
//            else
//            {
//                NSLog(@"添加设备1阶段，删除设备失败");
//                [MMProgressHUD dismissWithError:@"添加设备失败"];
//            }
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"error:%@",error);
//        }];
//    }
//}

//- (void)addOneDevice
//{
//    ipUrl = [Utitlity judgeipUrl];
//   
//    if(ipUrl)
//    {
//        
//        [MMProgressHUD showWithTitle:@"提示"
//                              status:@"添加设备中...."
//                 confirmationMessage:@"确定取消添加设备？"
//                         cancelBlock:^{
//                             [self cancleNode];
//                         }];
//
//        //超时处理
//        addTooLong = NO;
//        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            
//            if(!addTooLong)
//            {
//                NSLog(@"添加设备失败");
//                [MMProgressHUD dismissWithError:@"添加设备失败"];
//            }
//        });
//
//        
//        NSString *deviceStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=1",ipUrl];
//        
//        [Utitlity commonHTTPMethod:deviceStr responseType:stringType success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            
//             NSLog(@"添加设备responseObject:%@",responseObject);
//            
//            NSString * responseStr = [[NSString alloc] initWithBytes:[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding];
//            
//            NSLog(@"添加设备responseStr:%@",responseStr);
//            
//            NSArray *arr = [responseStr componentsSeparatedByString:@"\n"];
//            NSString *reponse = [arr lastObject];
//            NSDictionary *item = [reponse objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];//添加设备字典
//            
//            NSLog(@"add-item:%@",item);
//            NSString *status = item[@"state"];
//            if ([status isEqualToString:@"Success"])
//            {
//                NSLog(@"添加设备2阶段成功");
//                addTooLong = YES;
//                [MMProgressHUD dismissWithSuccess:@"添加成功"];
//                [resultItem addObject:item];
//            }else
//            {
//                NSLog(@"添加设备2阶段失败");
//                [MMProgressHUD dismissWithError:@"添加失败"];
//            }
//            
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"123error:%@",error);
//            [MMProgressHUD dismissWithSuccess:@"添加失败"];
//        }];
//        [super doneLoadingTableViewData:resultItem];
//    }
//    else
//    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前操作只限于局域网下执行" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
//        [alertView show];
//    }
//}

- (void)addOneDevice
{
    ipUrl = [Utitlity judgeipUrl];
    
    if(ipUrl)
    {
        
        [MMProgressHUD showWithTitle:@"提示"
                              status:@"添加设备中...."
                 confirmationMessage:@"确定取消添加设备？"
                         cancelBlock:^{
                             [self cancleNode];
                         }];
        
        //超时处理
        addTooLong = NO;
        /*
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            if(addTooLong)
            {
                NSLog(@"添加设备失败");
                [MMProgressHUD dismissWithError:@"添加设备失败"];
            }
        });*/
        
        //添加url
        NSString *deviceStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=1",ipUrl];
        NSURLRequest *theRequest = [NSURLRequest requestWithURL:
                                    [NSURL URLWithString:deviceStr]
                                                    cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                timeoutInterval:100.0];
        NSURLConnection *theConncetion=[[NSURLConnection alloc]
                                        initWithRequest:theRequest delegate:self];
        if(theConncetion)
        {
            //创建NSMutableData
            receivedData = [NSMutableData data];
            
            self.strMutableModeReqResponse = [[NSMutableString alloc] initWithString:@""];
            
        }else //创建失败
        {
            NSLog(@"url 创建失败");
        }
    }
}
//_________________________________________________________________

#pragma mark -----删除 delete a device
- (void)deleteOneDevice
{
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        deleteTooLong = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(!deleteTooLong)
            {
                [MMProgressHUD dismissWithError:@"删除设备超时"];
            }
        });
        
        NSLog(@"开始删除设备");
        NSString *deleStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=2",ipUrl];
        [Utitlity commonHTTPMethod:deleStr responseType:stringType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             if (!responseObject || ![responseObject isKindOfClass:[NSData class]]) return;
             
             NSLog(@"delete a device:%@",responseObject);
             
             NSString * responseStr = [[NSString alloc] initWithBytes:[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding];
             
             NSLog(@"delete-responseStr:%@",responseStr);
             //返回 {"state":"Success","data":{"ZID":"0"}}
             
             NSDictionary *item = [responseStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
             NSDictionary *dataDict = [item objectForKey:@"data"];
             NSString *zid = dataDict[@"ZID"];
             //NSString *uuid = dic[@"uuid"]; //没有返回 {"uuid":"xxx"}
             //NSString *infoStr = [NSString stringWithFormat:@"%@%@",uuid,zid];
             NSString *infoStr = zid;
             
             PersistableInfo *info = (PersistableInfo *)[PersistableInfo findFirstByCriteria:@"where uuid='%@'",infoStr];
             if(info)
             {
                 [PersistableInfo deleteByCriteria:@"where uuid = '%@'",zid];
             }
             
             NSString *status = item[@"state"];
             if ([status isEqualToString:@"Success"])
             {
                 NSLog(@"删除设备成功");
                 deleteTooLong = YES;
                 [MMProgressHUD dismissWithSuccess:@"删除成功"];
                 for (NSInteger i = 0; i<[resultItem count] ; i ++)
                 {
                     NSDictionary *itemDic = [resultItem objectAtIndex:i];
                     NSString *strItemZID = itemDic[@"ZID"];
                     if (strItemZID)
                     {
                         NSInteger nItemZID = [strItemZID integerValue];
                     
                         if (nItemZID == [zid integerValue])
                         {
                             [resultItem removeObjectAtIndex:i];
                             i--;
                         }
                     }
                 }
                 
             }
             else
             {
                 NSLog(@"删除设备失败");
                 [MMProgressHUD dismissWithError:@"删除失败"];
             }
             [super doneLoadingTableViewData:resultItem];
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前操作只限于局域网下执行" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
        [alertView show];
    }
}

//cancleNode
- (void)cancleNode
{
    ipUrl = [Utitlity judgeipUrl];
    
    if (ipUrl)
    {
        NSString *deviceStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=10",ipUrl];
        [Utitlity commonHTTPMethod:deviceStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([[responseObject[@"state"] lowercaseString] isEqualToString:@"success"]) {
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

-(CGFloat)rowHeight
{
    return 76;
}

#pragma mark-UITableView
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    static NSString *AutomationCellIdentifier = @"AutomationCellIdentifier";
    AutomationCell *cell = (AutomationCell*)[dataTableView dequeueReusableCellWithIdentifier:AutomationCellIdentifier];
    if (cell==nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"AutomationCell" owner:self options:nil]lastObject];
        [cell initView];
        cell.adelegate= self;
        cell.curtainCtrlView.hidden = YES;
    }
    NSMutableDictionary *rowData = [self.rows objectAtIndex:row];

//    NSMutableDictionary *muDic = [rowData mutableCopy];
    strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *zidStr = rowData[@"ZID"];
    NSString *appStr = [NSString stringWithFormat:@"%@%@",strUuid,zidStr];
    [rowData setObject:appStr forKey:@"uuid"];
    [cell setCellData:rowData];

//	NSUInteger row=[indexPath row];
//    return [self.rows objectAtIndex:row];
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSDictionary *item = [deviceList objectAtIndex:indexPath.row];
        
        [self deleteAFailDeviceToZid:[item[@"ZID"] intValue]];

    }
}

- (void)deleteAFailDeviceToZid:(int)zid
{
    ipUrl = [Utitlity judgeipUrl];
    
    if (ipUrl)
    {
        NSString *deleFailStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?ZID=%d&Mode=3",ipUrl,zid];
        [Utitlity commonHTTPMethod:deleFailStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self loadPageData:1];
                });
            }
            NSLog(@"reponseObject:%@",responseObject);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

#pragma mark-局域网界面刷新
- (void)updateDevStatusChangeWithHttp
{
//    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Node-5",@"Alias",@"1",@"DeviceType",@"99",@"Status",@"5",@"ZID", nil];
//    
//    NSString *zid = dic[@"ZID"];
//    NSInteger deviceType = [dic getIntegerValForKey:@"DeviceType"];
//    NSString *string = [[NSString alloc] init];
//    if ( deviceType <= 4 || deviceType >= 8)
//    {
//        for (int i = 0; i<[tcpResultItem count]; i++)
//        {
//            NSDictionary *item = [tcpResultItem objectAtIndex:i];
//            
//            if ([item[@"ZID"] isEqualToString:zid])
//            {
//                NSLog(@"item-http:%@",item);
//                string = item[@"uuid"];
//                [tcpResultItem replaceObjectAtIndex:i withObject:dic];
//            }
//        }
//    }
//   
////    NSString *infoStr = [NSString stringWithFormat:@"%@%@", [GlobalService sharedInstance].curOperationDeviceUUID,zid];
//    
//    PersistableInfo *info = (PersistableInfo *)[PersistableInfo findFirstByCriteria:@"where uuid='%@'",string];
//    if(info)
//    {
//        [PersistableInfo deleteByCriteria:@"where uuid = %@",string];
//    }
//    
//    [super doneLoadingTableViewData:tcpResultItem];
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *updateStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Status.cgi",ipUrl];
        
        [Utitlity commonHTTPMethod:updateStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"update:%@",responseObject);
            
            if ([[responseObject objectForKey:@"state"] isEqualToString:@"Success"])
            {
                @synchronized(resultItem)
                {
                    NSArray *updateList = [responseObject objectForKey:@"data"];
                    
                    NSLog(@"updatelistwith http:%@",updateList);
                    
                    if(updateList)
                    {
                        for (int i = 0;i <[updateList count];i++)
                        {
                            NSDictionary *upItem = [[updateList objectAtIndex:i] mutableCopy];
                            NSString *zid = [[upItem objectForKey:@"ZID"] lowercaseString];
                            NSInteger deviceType = [upItem getIntegerValForKey:@"DeviceType"];
                            
                            if ( deviceType <= 4 || deviceType >= 8)
                            {
                                for (int i = 0; i<[resultItem count]; i++)
                                {
                                    NSDictionary *reItem = [resultItem objectAtIndex:i];
                                    
                                    if ([reItem[@"ZID"] isEqualToString:zid])
                                    {
                                        NSLog(@"item-http:%@",reItem);
                                        [resultItem replaceObjectAtIndex:i withObject:upItem];
                                    }
                                }
                            }
                        }
                        
                    }
                }
            }
            //刷新列表
            NSLog(@"update-resultItem:%@",resultItem);
            [super doneLoadingTableViewData:resultItem];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    
    
    
}

#pragma mark-tcp情况下刷新界面
- (void)updateDevStatusChangeData:(NSNotification *)data
{
    NSArray *updateList = [data.userInfo objectForKey:NOTIFICATION_USERINFO_UPDATEDATA];
    NSLog(@"updateList:%@",updateList);
    
    ipUrl = [Utitlity judgeipUrl];
    
    if (!ipUrl)
    {
        @synchronized(tcpResultItem)
        {
            if (updateList)
            {
                for (int i = 0; i< [updateList count]; i ++)
                {
                    NSLog(@"对比中");
                    NSDictionary *upItem = [[updateList objectAtIndex:i] mutableCopy];
                    NSString *zid = [[upItem objectForKey:@"ZID"] lowercaseString];
                    NSLog(@"update-zid:%@",zid);
                    
                    NSInteger deviceType = [upItem getIntegerValForKey:@"DeviceType"];
                    if ( deviceType <= 4 || deviceType >= 8)
                    {
                        for (int i = 0; i<[tcpResultItem count]; i++)
                        {
                            NSDictionary *tItem = [tcpResultItem objectAtIndex:i];
                            
                            if ([tItem[@"ZID"] isEqualToString:zid])
                            {
                                NSLog(@"item-tcp:%@",tItem);
                                [tcpResultItem replaceObjectAtIndex:i withObject:upItem];
                            }
                        }
                    }
                }
                
                NSLog(@"update-tcpResultItem:%@",tcpResultItem);
                [super doneLoadingTableViewData:tcpResultItem];
            }
        }

    }
}

#pragma mark-load datasouce
-(NSArray *)loadPageData:(int)page
{
    [activity startAnimating];
    
    ipUrl = [Utitlity judgeipUrl];
    isLoaded = NO;
//    __block int isLoaded = NO;
    if (ipUrl)
    {
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Get.cgi?Get=1",ipUrl];
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
            [activity stopAnimating];
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
//            NSMutableArray *result = [NSMutableArray array];
            NSMutableString *zids = [NSMutableString string];
            {
                isLoaded = YES;
                deviceList = responseObject[@"data"];
                NSLog(@"deviceList-----------:%@",deviceList);

                for (int i = 0; i< [deviceList count]; i ++)
                {
                    NSMutableDictionary *item = [[deviceList objectAtIndex:i] mutableCopy];
                    NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                    
                    if ( deviceType == 1 || deviceType == 2 || deviceType >= 7)
                    {
                        //8是窗帘类型 Device_Type_MOTOR, VALUE=0关  99开  -1停
                        [zids appendFormat:@"%@,",[item objectForKey:@"ZID"]];
                        [resultItem addObject:item];
                    }
                }
            }
            
            if ([resultItem count] > 0)
            {
                [super doneLoadingTableViewData:resultItem];
                self.ids = zids;
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        //NSString *loadStr = @"/Get.cgi?Get=1";
        //[[CMDDataProcessor sharedInstance] sendCGIURLCMDWithData:(void *)[loadStr UTF8String] callRecivedBlock:^(id data) {
        [[CMDDataProcessor sharedInstance] getDeviceListResultDataWithDataRecivedBlock:^(id data) {

            
            if (!data || ![data isKindOfClass:[NSDictionary class]]) return;
            if ([data[@"state"] isEqualToString:@"Success"])
            {
                [activity stopAnimating];
                tcpResultItem = [[NSMutableArray alloc] init];
//                NSMutableArray *result = [[NSMutableArray alloc] init];
                NSMutableString *zids = [[NSMutableString alloc] init];
                {
                    isLoaded = YES;
                    DLog(@"");
                    deviceList = data[@"data"];
                    NSLog(@"deviceList1111-----------:%@",deviceList);
                    for (int i = 0 ; i< [deviceList count]; i ++)
                    {
                        NSMutableDictionary *item = [[deviceList objectAtIndex:i] mutableCopy];
                        NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                        
                        if ( deviceType <= 4 || deviceType >= 7) {
                            //8是窗帘类型 Device_Type_MOTOR, VALUE=0关  99开  -1停
                            [zids appendFormat:@"%@,",[item objectForKey:@"ZID"]];
                            [tcpResultItem addObject:item];
                        }
                    }
                }
    
                if ([tcpResultItem count] > 0 )
                {
                    [super doneLoadingTableViewData:tcpResultItem];
                    self.ids = zids;
                }
            }
        }];
    }
    //再次请求数据
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!isLoaded)
        {
            NSLog(@"再次获取列表");
            [self loadPageData:1];
        }
    });
    
    /*if (1 == 2) {
        [WISInterfaces wis_send_private_cmd:[GlobalInfo sharedInstance].m_CmdSock cmdId:WIS_CMD_V2_DEV_LIST_GET data: (void *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String] len:32 uuid:(char *)[[GlobalService sharedInstance].curOperationDeviceUUID UTF8String]];
    }*/

    /*
    [[SetData sharedInstance] getDataWithDataRecivedBlock:^(id data){
        [activity stopAnimating];
        NSArray *array = (NSArray *)data;
        NSMutableArray *result = [NSMutableArray array];
        NSMutableString *zids = [NSMutableString string];
        for (NSDictionary *dict in array) {
            
            NSString *kind = [[dict objectForKey:@"kind"] lowercaseString];
            NSString *zid = [dict objectForKey:@"zid"];
            if ([kind rangeOfString:@"sensor"].length>0 || [kind rangeOfString:@"avcontrolpoint"].length>0 ||[kind rangeOfString:@"thermostat"].length>0) {
                continue;
            }else{
                [zids appendFormat:@"%@,",zid];
            }
            
            AutomationCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"AutomationCell" owner:self options:nil]lastObject];
            [cell initView];
            [cell setData:dict];
            cell.delegate= self;
            [result addObject:cell];
       }
        [super doneLoadingTableViewData:result];
        self.ids = zids;
        
        [self updateStatusData];
    }];
    */
    return nil;
}

- (void)presentAlertViewMatchStr:(NSString *)string
{
    int number = [string intValue];
    if (number == 505) {
        [MMProgressHUD showWithTitle:@"操作超时"];
    }else if (number == 506)
    {
        [MMProgressHUD showWithTitle:@"处理错误"];
    }else if(number == 507){
        [MMProgressHUD showWithTitle:@"重复加入同一个Z-Wave设备"];
    }else if (number == 510){
        [MMProgressHUD showWithTitle:@"上一操作未正常结束"];
    }else if(number == 511){
        [MMProgressHUD showWithTitle:@"设备已失效"];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MMProgressHUD dismiss];
    });
}

- (void)revServerCMDResponseData:(id)data {


    /*
    NSArray *array = (NSArray *)data;


    for (NSDictionary *dict in array) {
        
        NSString *kind = [[dict objectForKey:@"kind"] lowercaseString];
        NSString *zid = [dict objectForKey:@"zid"];
        if ([kind rangeOfString:@"sensor"].length>0 || [kind rangeOfString:@"avcontrolpoint"].length>0 ||[kind rangeOfString:@"thermostat"].length>0) {
            continue;
        }else{
            [zids appendFormat:@"%@,",zid];
        }
        
        AutomationCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"AutomationCell" owner:self options:nil]lastObject];
        [cell initView];
        [cell setData:dict];
        cell.delegate= self;
        [result addObject:cell];
    }
    */

    
    //[self updateStatusData];

}

#pragma mark-all open/close
//all open
- (void)allDeviceOpen
{
    [timer invalidate];
    timer = nil;
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Switch.cgi?ZID=255&Value=255",ipUrl];
        
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"respone:%@",responseObject);
            
            NSMutableArray *result = [[NSMutableArray alloc] init];
            for (int i = 0; i< [self.rows count]; i ++)
            {
                
                NSMutableDictionary *item = [self.rows objectAtIndex:i] ;
                NSLog(@"item:%@",item);
                NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                if (deviceType <= 4 ||deviceType >= 8)
                {
                    [item setObject:@"1" forKey:@"Status"];
                    
                    if(deviceType == 2)
                    {
                        [item setObject:@"255" forKey:@"Value"];
                    }
                }
                
                [result addObject:item];
            }
             [super doneLoadingTableViewData:result];

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        NSString *zid = [NSString stringWithFormat:@"%@",@"255"];
        WisDevSwitchSetCmd cmd;
        strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String]);
        strcpy(cmd.did, [zid UTF8String]);
        cmd.value = 255;
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_DEV_SWITCH_SET cmdLength:sizeof(WisDevSwitchSetCmd)  withData:&cmd callRecivedBlock:^(id jsondata) {
            
            NSLog(@"respone:%@",jsondata);

            if (jsondata)
            {
                NSMutableArray *result = [[NSMutableArray alloc] init];
                for (int i = 0; i< [self.rows count]; i ++)
                {
                    
                    NSMutableDictionary *item = [self.rows objectAtIndex:i] ;
                    NSLog(@"item:%@",item);
                    NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                    if (deviceType <= 4 ||deviceType >= 8)
                    {
                        [item setObject:@"1" forKey:@"Status"];
                        
                        if(deviceType == 2)
                        {
                            [item setObject:@"255" forKey:@"Value"];
                        }
                    }
                    
                    [result addObject:item];
                }
                [super doneLoadingTableViewData:result];
            }
        }];
    }
}

- (void)allDeviceClosed
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Switch.cgi?ZID=255&Value=0",ipUrl];
        
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            NSMutableArray *result = [[NSMutableArray alloc] init];
            for (int i = 0; i< [self.rows count]; i ++)
            {
                NSMutableDictionary *item = [self.rows objectAtIndex:i] ;
                NSLog(@"item:%@",item);
                NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                if (deviceType <= 4 ||deviceType >= 8)
                {
                    [item setObject:@"0" forKey:@"Status"];
                    
                    if(deviceType == 2)
                    {
                        [item setObject:@"0" forKey:@"Value"];
                    }
                }
                [result addObject:item];
            }

            [super doneLoadingTableViewData:result];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        NSString *zid = [NSString stringWithFormat:@"%@",@"255"];
        WisDevSwitchSetCmd cmd;
        strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String]);
        strcpy(cmd.did, [zid UTF8String]);
        cmd.value = 0;
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_DEV_SWITCH_SET cmdLength:sizeof(WisDevSwitchSetCmd)  withData:&cmd callRecivedBlock:^(id jsondata) {
            
            NSLog(@"respone:%@",jsondata);
            if (jsondata)
            {
                NSMutableArray *result = [[NSMutableArray alloc] init];
                for (int i = 0; i< [self.rows count]; i ++)
                {
                    NSMutableDictionary *item = [self.rows objectAtIndex:i] ;
                    NSLog(@"item:%@",item);
                    NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                    if (deviceType <= 4 ||deviceType >= 8)
                    {
                        [item setObject:@"0" forKey:@"Status"];
                        
                        if(deviceType == 2)
                        {
                            [item setObject:@"0" forKey:@"Value"];
                        }
                    }
                    [result addObject:item];
                }
                [super doneLoadingTableViewData:result];
            }
        }];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    ipUrl = [Utitlity judgeipUrl];
    NSLog(@"indxe:%ld",(long)buttonIndex);
    if (actionSheet.tag == 100)
    {
        if (buttonIndex < [cameras count])
        {
            
            NSString *streamURL = [[cameras objectAtIndex:buttonIndex] objectForKey:@"VideoStream"];
            if (cameraView && ![cameraView.camURL isEqualToString:streamURL]) {
                [cameraView removeFromSuperview];
                cameraView = nil;
            }
            
            if (!cameraView) {
                cameraView = [[[NSBundle mainBundle] loadNibNamed:@"CameraWebView" owner:self options:nil]lastObject];
                cameraView.camURL = streamURL;
                cameraView.frame = CGRectMake(5, 5, 310, 235);
                [self.view addSubview:cameraView];
                dataTableView.frame = CGRectMake(0, 245, 320, self.view.frame.size.height - 245 - 60);
                [cameraView loadRequest];
            }
        }
    }else if (actionSheet.tag == 200)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"只有在局域网情况下才能删除或者添加设备" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        NSLog(@"%ld",(long)buttonIndex);
        if (buttonIndex == 0)
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请按住设备上的按钮" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alertView.tag = 200;
            [alertView show];
        }
        else if (buttonIndex == 1)
        {
            if (ipUrl)
            {
                [MMProgressHUD showWithTitle:@"提示"
                                      status:@"请点击设备上的按钮"
                         confirmationMessage:@"确定取消删除设备？"
                                 cancelBlock:^{
                                     [self cancleNode];
                                 }];
                [self deleteOneDevice];
            }
            else
            {
                [alert show];
            }
        }
        else if (buttonIndex == 2)
        {
           [self allDeviceOpen];
        }
        else if (buttonIndex == 3)
        {
            [self allDeviceClosed];
        }
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)
    {
        if (buttonIndex == 1)
        {
            [self loadPageData:1];
        }
    }else if(alertView.tag == 200)
    {
        if (buttonIndex == 1)
        {
            [self addOneDevice];
        }
    }
    
}

#pragma mark - AutomationCell Delegate

-(void)changeInfo:(NSDictionary *)data cell:(AutomationCell*)cell
{
    ChangeInfoDialog  *yijianview = [[[NSBundle mainBundle] loadNibNamed:@"ChangeInfoDialog" owner:self options:nil]lastObject];
    yijianview.delegate = self;
    [yijianview initView];
    [yijianview setRoomDataList:_roomDataList];
    [yijianview setData:data cell:cell];
    [yijianview pageStart];
}

#pragma mark
- (void)changeDataDic:(NSDictionary *)dic
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        int i;
        for (i = 0; i < [tcpResultItem count];i++)
        {
            NSDictionary *proDic = [tcpResultItem objectAtIndex:i];
            if([dic[@"ZID"] isEqualToString:proDic[@"ZID"]])
            {
                //替换修改的
                NSMutableDictionary *reDic = [dic mutableCopy];
                NSString *sensorStr = [reDic objectForKey:@"SensorType"];
                int aboveDeviceType = [[reDic objectForKey:@"DeviceType"] intValue];
                int aboveZid = [[reDic objectForKey:@"ZID"] intValue];
                NSString *name = [reDic objectForKey:@"Alias"];
                
                //如果上面是sensor，还带有温度计，一起修改
                if ((i+1) < [tcpResultItem count])
                {
                    NSMutableDictionary *nextDic = [[tcpResultItem objectAtIndex:i+1] mutableCopy];
                    NSString *nextSensorStr = [nextDic objectForKey:@"SensorType"];
                    int nextZid = [[nextDic objectForKey:@"ZID"] intValue];

                    int deviceType = [nextDic[@"DeviceType"] intValue];
                    
                    if (nextSensorStr && sensorStr && deviceType == 4  && aboveDeviceType == 3 && aboveZid == nextZid)
                    {
                        [nextDic setValue:name forKey:@"Alias"];
                   
                        //gengxin  mingcheng
                        [self updateNameWithzid:[nextDic objectForKey:@"ZID"] alais:name];
                        
                        [tcpResultItem replaceObjectAtIndex:i+1 withObject:nextDic];
                    }
                }
                
                [tcpResultItem replaceObjectAtIndex:i withObject:reDic];
            }
        }
        
        [MMProgressHUD showWithStatus:@"修改名字中...."];
        [MMProgressHUD dismissWithSuccess:@"修改名字成功"];
        
        [super doneLoadingTableViewData:tcpResultItem];
    }
    else
    {
        [MMProgressHUD showWithTitle:@"修改名称错误" status:@"只能在局域网内进行修改"];
        [MMProgressHUD dismissAfterDelay:1];
    }
    
}

- (void)changeInfoDialogWithData:(NSDictionary *)dic changeToRoom:(RoomItemModel *)changeRoomData {
    
    for (NSInteger i=0; i<self.rows.count; i++) {
        NSDictionary *data = self.rows[i];
        if ([data[@"ZID"] isEqualToString:dic[@"ZID"]]) {
            
            NSNumber *rooId = dic[@"Room"];
            NSMutableDictionary *reDic = [data mutableCopy];
            reDic[@"Room"] = rooId;
            [self.rows replaceObjectAtIndex:i withObject:reDic];
            [dataTableView reloadData];
            break;
        }
    }
}

- (void)updateNameWithzid:(NSString*)zid alais:(NSString *)alais
{
    
    ipUrl = [Utitlity judgeipUrl];
    NSLog(@"ipurl:%@",ipUrl);
    if (ipUrl)
    {
        NSString *updataNameStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Set.cgi?OP=1&ID=%@&Name=%@",ipUrl,zid,alais];
        NSString * encodingString = [updataNameStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"encodingString:%@",encodingString);
        [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"updataNameStr responseObject:%@",responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    
    
}

#pragma mark-NSURLDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

//fen pi ci
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
{
    if (!data) return;
    [receivedData appendData:data];
    
    NSLog(@"connection data len:%ld :%@", data.length, data);
   
    NSString *responseStr = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    if (!responseStr) return;
    [receivedData setData:nil];
    
    [self.strMutableModeReqResponse appendString:responseStr];
    NSLog(@"%@", self.strMutableModeReqResponse);
    BOOL isBreakWhile = NO;
    while (1) {
        
        if (isBreakWhile) {
            break;
        }

    NSRange range = [self.strMutableModeReqResponse rangeOfString:@"\n"];
    if (range.location == NSNotFound) {
        isBreakWhile = YES;
        range = NSMakeRange(0, 0);
        responseStr = [self.strMutableModeReqResponse substringFromIndex:range.location];
        
    }else
        responseStr = [self.strMutableModeReqResponse substringToIndex:range.location];
        if (responseStr.length == 0) break;
        
    NSLog(@"reciveDataStr:%@",responseStr);
    [self.strMutableModeReqResponse setString:[self.strMutableModeReqResponse substringFromIndex:range.location+1]];
    
    NSString *string2 = @"\"state\"";
    range = [responseStr rangeOfString:string2 options:NSBackwardsSearch];
    if (range.location == NSNotFound) {
        continue;
    }
    
    //NSString *endStr = [responseStr substringFromIndex:range.location];
    NSDictionary *endDic = [responseStr objectFromJSONString];
    
    NSLog(@"endDic:%@",endDic);
    
    if (![endDic[@"state"] isEqualToString:@"Success"])
    {
        NSLog(@"1234567890000");
        NSString *statusStr = endDic[@"info"];
        
        NSLog(@"statusStr:%@",statusStr);
        [MMProgressHUD showWithTitle:@"添加" status:statusStr];
    }
    else if ([endDic[@"state"] isEqualToString:@"Success"])
    {
        NSLog(@"123456789-add");
        addTooLong = YES;
        [MMProgressHUD dismissWithSuccess:@"添加成功" title:@"添加"];
        
        NSArray *successArr = endDic[@"data"];
        for (NSDictionary *item in successArr) {
    
            NSMutableDictionary *devDic = [item mutableCopy];
            NSLog(@"successDic:%@",devDic);
            if (devDic) [resultItem addObject:devDic];
        }
        
        NSLog(@"add-resultItem:%@",resultItem);
        
        [super doneLoadingTableViewData:resultItem];//添加成功后刷新
        
        break;
    }
    else if ([endDic[@"state"] isEqualToString:@"Fail"])
    {
        NSLog(@"123456789-fail");
        addTooLong = YES;
        [MMProgressHUD dismissWithSuccess:@"添加失败" title:@"添加"];
    }
    }
}

//fail
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"NSURLConnection error:%@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"NSURLConnection success %lu byte receive",(unsigned long)[receivedData length]);
}

@end
